﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
using System.Collections.Specialized;

namespace CanalDeNoticiasMSDNv4
{
    /// <summary>
    /// An ObservableCollection that allows us to suspend for enhancing it during data binding.
    /// </summary>
    /// <typeparam name="T">The type of object that the collection will contain</typeparam>
    public class SuspendableObservableCollection<T> : ObservableCollection<T>
    {
        object _lock = new object();
        private bool _suspended;

        private bool _changedDuringSuspend;

        /// <summary>
        /// Suspends the CollectionChanged event.
        /// </summary>
        public void Suspend()
        {
            lock (_lock)
            {
                _suspended = true;
            }
        }

        /// <summary>
        /// Resumes the CollectionChanged event. If the collection was changed during suspension 
        /// will fire a CollectionChanged event with <see cref="NotifyCollectionChangedAction.Reset"/>
        /// as EventArgs parameter.
        /// </summary>
        public void Resume()
        {
            lock (_lock)
            {
                _suspended = false;
                if (_changedDuringSuspend)
                {
                    _changedDuringSuspend = false;
                    base.OnCollectionChanged(new NotifyCollectionChangedEventArgs(
                       NotifyCollectionChangedAction.Reset));
                }
            }
        }

        protected override void OnCollectionChanged(
            NotifyCollectionChangedEventArgs args)
        {
            lock (_lock)
            {
                if (!_suspended)
                {
                    base.OnCollectionChanged(args);
                }
                else
                {
                    _changedDuringSuspend = true;
                }
            }
        }
    }
}
